/* 
  全局变量
*/
// 商品列表
let goodEle = `

`
// 分页总数
let totalNum = 0


/* 
  返回顶部
*/
function goTop() {
  document.querySelectorAll('#toStart>ul>li')[1].onclick = function () {
    let timer = setInterval(function () {
      document.documentElement.scrollTop -= 20
      if (document.documentElement.scrollTop <= 0) {
        document.documentElement.scrollTop = 0
        clearInterval(timer)
      }
    }, 10)
  }
}

/* 
  返回首页
*/
function gohome() {
  document.querySelectorAll('#toStart>ul>li')[2].onclick = function () {
    // 显示首页
    document.querySelector('.goodsListHeader').innerHTML = '当前位置：首页'
    let liEle = document.querySelectorAll('.banner>ul>li')
    for (let i = 0; i < liEle.length; i++) {
      liEle[i].setAttribute('class', '')
    }
    document.querySelectorAll('.banner>ul>li')[0].setAttribute('class', 'active1')
    document.querySelector('.goodsList').innerHTML = goodEle
    document.querySelector('.more>button').setAttribute('id', '')

    // 滚动
    let timer = setInterval(function () {
      document.documentElement.scrollTop -= 20
      if (document.documentElement.scrollTop <= 0) {
        document.documentElement.scrollTop = 0
        clearInterval(timer)
      }
    }, 10)
    this.setAttribute('class', 'show')
  }
}


/* 
  设置分类的动态显示与隐藏
*/
function banner() {
  let bannerELe = document.querySelector('.banner')
  bannerELe.addEventListener('mousemove', function (e) {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.getAttribute('class') == 'fenleiitem' || target.innerHTML == '分类' || target.getAttribute('class') == 'classification') {
      let fenleiELe = document.querySelector('.classification')
      fenleiELe.removeAttribute('id')
    }
  })
  bannerELe.addEventListener('mouseout', function (e) {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.getAttribute('class') == 'fenleiitem' || target.innerHTML == '分类' || target.getAttribute('class') == 'classification') {
      let fenleiELe = document.querySelector('.classification')
      fenleiELe.setAttribute('id', 'show')
    }
  })
}

/* 
  获取所有分类
*/
function getFenLei() {
  myAjaxPromise({
    method: 'get',
    url: 'http://api.yuguoxy.com/api/shop/category/list',
  }).then(res => {
    let fenleiObj = res.resultInfo.list
    let spanEle = ''
    fenleiObj.forEach(item => {
      let span = `
      <span class="fenleiitem" data-index="${item.id}">${item.name}</span>
      `
      spanEle += span
    });
    document.querySelector('.classification').innerHTML = spanEle

  }).catch(err => {
    console.log(err);
  })
}

/* 
  获取轮播图
*/
function getbanner() {
  myAjaxPromise({
    method: 'get',
    url: 'http://api.yuguoxy.com/api/shop/banner',
  }).then(res => {
    let imgObj = res.resultInfo.list

    let imgEle = ''
    imgObj.forEach(item => {
      let img = `
      <div class="swiper-slide" data-index="${item.id}">
        <img src="${item.url}" alt="">
      </div>
      `
      imgEle += img
    });
    document.querySelector('.swiper-wrapper').innerHTML = imgEle
    /* 
      初始化轮播图
    */
    let mySwiper = new Swiper('.swiper', {
      loop: true,
      pagination: {
        el: '.swiper-pagination',
        clickable: true,
      },
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },
      autoplay: { disableOnInteraction: false },
    })

  }).catch(err => {
    console.log(err);
  })
}
/* 
  获取商品列表
*/
function getGoods() {
  myAjaxPromise({
    method: 'get',
    url: 'http://api.yuguoxy.com/api/shop/list',
    data: {
      pageSize: 8,
      pageNo: 1
    }
  }).then(res => {
    totalNum = res.resultInfo.totalNum
    let goodsObj = res.resultInfo
    goodsObj.list.forEach(item => {
      let goods = `
      <div class="box" data-index="${item.id}">
        <img src="${item.picture}" alt="">
        <h3>${item.product}</h3>
        <div>
          <span>
            <span>秒杀价:${item.price}</span> <span>原价:${item.price}</span>
          </span>
          <span>${item.categoryname}</span>
        </div>
      </div>
      `
      goodEle += goods
    });
    document.querySelector('.goodsList').innerHTML = goodEle
  }).catch(err => {
    console.log(err);
  })
}

/* 
  加载更多
*/
function showMore() {
  let addNum = 1
  document.querySelector('.more>button').onclick = function () {
    if (addNum < totalNum) {
      myAjaxPromise({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/shop/list',
        data: {
          pageSize: 8,
          pageNo: ++addNum
        }
      }).then(res => {
        totalNum = res.resultInfo.totalNum
        let goodsObj = res.resultInfo
        goodsObj.list.forEach(item => {
          let goods = `
          <div class="box" data-index="${item.id}">
            <img src="${item.picture}" alt="">
            <h3>${item.product}</h3>
            <div>
              <span>
                <span>秒杀价:${item.price}</span> <span>原价:${item.price}</span>
              </span>
              <span>${item.categoryname}</span>
            </div>
          </div>
          `
          goodEle += goods
        });
        document.querySelector('.goodsList').innerHTML = goodEle
      }).catch(err => {
        console.log(err);
      })
    } else {
      document.querySelector('.more>button').innerHTML = '没有更多了'
    }
  }
}

/* 
  查看类型所有商品列表
*/
function showFenleiList() {
  document.querySelector('.classification').addEventListener('click', function (e) {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.getAttribute('data-index')) {
      let index = target.getAttribute('data-index')
      myAjaxPromise({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/shop/list/category',
        data: {
          categoryId: index
        }
      }).then(res => {
        totalNum = res.resultInfo.totalNum
        // 改变当前位置
        document.querySelector('.goodsListHeader').innerHTML = `当前位置：分类/${res.resultInfo.list[0].categoryname}`
        let fenleiGoodsList = `
        
        `
        let goodsObj = res.resultInfo.list
        goodsObj.forEach(item => {
          let goods = `
          <div class="box" data-index="${item.id}">
            <img src="${item.picture}" alt="">
            <h3>${item.product}</h3>
            <div>
              <span>
                <span>秒杀价:${item.price}</span> <span>原价:${item.price}</span>
              </span>
              <span>${item.categoryname}</span>
            </div>
          </div>
          `
          fenleiGoodsList += goods
        });

        let liEle = document.querySelectorAll('.banner>ul>li')
        for (let i = 0; i < liEle.length; i++) {
          liEle[i].setAttribute('class', '')
        }
        liEle[2].setAttribute('class', 'active1')
        // 隐藏查看更多
        document.querySelector('.more>button').setAttribute('id', 'show')

        to()
        document.querySelector('.goodsList').innerHTML = fenleiGoodsList

      }).catch(err => {
        console.log(err);
      })
    }
  })
}

/* 
  显示首页
*/
function aaaa() {  
  document.querySelectorAll('.banner>ul>li')[0].onclick = function () {
    document.querySelector('.goodsListHeader').innerHTML = '当前位置：首页'
    let liEle = document.querySelectorAll('.banner>ul>li')
    for (let i = 0; i < liEle.length; i++) {
      liEle[i].setAttribute('class', '')
    }
    this.setAttribute('class', 'active1')
    document.querySelector('.goodsList').innerHTML = goodEle
    document.querySelector('.more>button').setAttribute('id', '')
  }
}
aaaa()

/* 
  点击收索进行收索
*/
function search() {
  document.querySelector('.search').addEventListener('click', function (e) {
    e = e || window.event
    let target = e.target || e.srcElement

    if (target.innerHTML == '搜索') {
      a()
    }
  })
}

/* 
  实现点击回车收索
*/
function keysearch() {
  document.onkeydown = function (e) {
    e = e || window.event
    if (e.keyCode == 13) {
      a()
    }
  }
}

/* 
  收索功能
*/
function a() {
  myAjaxPromise({
    method: 'get',
    url: 'http://api.yuguoxy.com/api/shop/list',
    data: {
      pageSize: 10000,
      pageNo: 1
    }
  }).then(res => {
    let searchMsg = document.querySelector('.search>input').value
    let searchList = ''
    if (searchMsg == '') {
      for (let i = 0; i < res.resultInfo.list.length; i++) {
        let searchGoods = `
        <div class="box" data-index="${res.resultInfo.list[i].id}">
          <img src="${res.resultInfo.list[i].picture}" alt="">
          <h3>${res.resultInfo.list[i].product}</h3>
          <div>
            <span>
              <span>秒杀价:${res.resultInfo.list[i].price}</span> <span>原价:${res.resultInfo.list[i].price}</span>
            </span>
            <span>${res.resultInfo.list[i].categoryname}</span>
          </div>
        </div>
        `
        searchList += searchGoods
        searchMsg = '所有商品'
      }
    } else {
      for (let i = 0; i < res.resultInfo.list.length; i++) {
        let arr = res.resultInfo.list[i].product
        if (arr.indexOf(searchMsg) != -1) {
          let searchGoods = `
          <div class="box" data-index="${res.resultInfo.list[i].id}">
            <img src="${res.resultInfo.list[i].picture}" alt="">
            <h3>${res.resultInfo.list[i].product}</h3>
            <div>
              <span>
                <span>秒杀价:${res.resultInfo.list[i].price}</span> <span>原价:${res.resultInfo.list[i].price}</span>
              </span>
              <span>${res.resultInfo.list[i].categoryname}</span>
            </div>
          </div>
          `
          searchList += searchGoods
        }
      }
    }
    if (searchList == '') {
      document.querySelector('.goodsListHeader').innerHTML = `当前位置：搜索 ==> ${searchMsg}(为查询到结果)`
    } else {
      document.querySelector('.goodsListHeader').innerHTML = `当前位置：搜索 ==> ${searchMsg}`
    }
    document.querySelector('.goodsList').innerHTML = searchList
    // 隐藏查看更多
    document.querySelector('.more>button').setAttribute('id', 'show')
    // 清空搜索框
    document.querySelector('.search>input').value = ''
    to()
  }).catch(err => {
    console.log(err);
  })
}

/* 
  判断当前位置离顶距离，改变当前位置显示位置
*/
function showweizhi() {
  onscroll = function () {
    if (document.documentElement.scrollTop > 700) {
      document.querySelector('.goodsListHeader').setAttribute('class', 'goodsListHeader top')
    }
    if (document.documentElement.scrollTop <= 700) {
      document.querySelector('.goodsListHeader').setAttribute('class', 'goodsListHeader')
    }
  }
}

/* 
  登录
*/
function login() {

  // 打开登录窗口
  document.querySelector('.userMessage>span:nth-child(1)').onclick = function (e) {
    if (e.target.innerHTML == '登录') {
      document.querySelector('.login').setAttribute('class', 'login')
    }
    /* 
      点击取消登录窗口
    */
    document.querySelector('.login>.esc').onclick = function () {
      document.querySelector('.login').setAttribute('class', 'login show')
      document.querySelector('.login>input[name="username"]').value = ''
      document.querySelector('.login>input[name="pwd"]').value = ''
      document.querySelector('.user').innerHTML = ''
      document.querySelector('.pwd').innerHTML = ''
    }
  }

  document.querySelector('.userlogin').addEventListener('click', function () {
    yanzheng()
  })

  // 退出与注册
  document.querySelector('.userMessage>span:nth-child(2)').onclick = function (e) {
    if (e.target.innerHTML == '退出') {
      myAjaxPromise({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/logout',
      }).then(res => {
        if (res.resultCode == 1) {
          removeCookie('username')
          userinfo()
        }
    
      }).catch(err => {
        console.log(err);
      })
    }
    if (e.target.innerHTML == '注册') {
      document.querySelector('.reg').setAttribute('class', 'reg')
      /* 
        点击取消登录窗口
      */
      document.querySelector('.reg .userreg').addEventListener('click', function () {
        yanzheng('reg')
      })
      document.querySelector('.reg .esc').onclick = function () {
        document.querySelector('.reg').setAttribute('class', 'reg show')
        document.querySelector('.reg>input[name="username"]').value = ''
        document.querySelector('.reg>input[name="pwd"]').value = ''
        document.querySelector('.user').innerHTML = ''
        document.querySelector('.pwd').innerHTML = ''

      }
    }
  }


}

/* 
  用户名与密码验证
*/
function yanzheng(reg) {
  if (reg != 'reg') {
    // 非空验证
    let name = document.querySelector('.login>input[name="username"]').value
    let pwd = document.querySelector('.login>input[name="pwd"]').value
    if (name == '') {
      document.querySelector('.user').innerHTML = '用户名不能为空'
    }
    if (pwd == '') {
      document.querySelector('.pwd').innerHTML = '密码不能为空'
    }
    if (name != '' && pwd != '') {
      // 用户名
      let username = /^.{3,5}$/
      if (!username.test(name)) {
        document.querySelector('.user').innerHTML = '用户名3至5位'
        return
      }
      // 密码
      let userpwd = /^[a-zA-Z0-9]{5,10}$/
      if (!userpwd.test(pwd)) {
        document.querySelector('.pwd').innerHTML = '密码5-10位,含数字英文字母'
        return
      }
      myAjaxPromise({
        method: 'post',
        url: 'http://api.yuguoxy.com/api/login',
        data: {
          username: name,
          password: pwd
        }
      }).then(res => {
        if (res.resultCode == 1) {
          let usermsg = res.resultInfo.username
          document.querySelector('.login>input[name="username"]').value = ''
          document.querySelector('.login>input[name="pwd"]').value = ''
          document.querySelector('.user').innerHTML = ''
          document.querySelector('.pwd').innerHTML = ''
          saveCookie('username', usermsg, 600000)
          document.querySelector('.login').setAttribute('class', 'login show')
          userinfo()
        } else {
          alert('用户名或密码错误')
        }

      }).catch(err => {
        console.log(err);
      })

    }
  } else {
    // 非空验证
    let name = document.querySelector('.reg>input[name="username"]').value
    let pwd = document.querySelector('.reg>input[name="pwd"]').value
    if (name == '') {
      document.querySelector('.user').innerHTML = '用户名不能为空'
    }
    if (pwd == '') {
      document.querySelector('.pwd').innerHTML = '密码不能为空'
    }
    if (name != '' && pwd != '') {
      // 用户名
      let username = /^.{3,5}$/
      if (!username.test(name)) {
        document.querySelector('.user').innerHTML = '用户名3至5位'
        return
      }
      // 密码
      let userpwd = /^[a-zA-Z0-9]{5,10}$/
      if (!userpwd.test(pwd)) {
        document.querySelector('.pwd').innerHTML = '密码5-10位,含数字英文字母'
        return
      }
      myAjaxPromise({
        method: 'post',
        url: 'http://api.yuguoxy.com/api/sign',
        data: {
          username: name,
          password: pwd,
          headerimg: 'http://test.yuguoxy.com/static/img/index-logo.png'
        }
      }).then(res => {
        if (res.resultCode == 1) {
          let usermsg = name
          saveCookie('username', usermsg, 600000)
          document.querySelector('.reg').setAttribute('class', 'reg show')
          userinfo()
        } else {
          alert('注册出错辣')
        }
      }).catch(err => {
        console.log(err);
      })
    }
  }

}


/* 
  判断用户是否登录
 */
function userinfo() {
  if (getCookie('username')) {
    document.querySelector('.userMessage').innerHTML = `
      <span> ${getCookie('username')} </span>
      <span>退出</span>
    `
    login()
    return true
  } else {
    document.querySelector('.userMessage').innerHTML = `
      <span>登录</span>
      <span>注册</span>
    `
    login()
    return false
  }
}


/* 
  查看详情
 */

function showinfo() {
  document.querySelector('.goodsList').addEventListener('click', function (e) {
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.getAttribute('class') == 'box') {
      let index = target.getAttribute('data-index')
      myAjaxPromise({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/shop/find',
        data: {
          id: index
        }
      }).then(res => {
        let goodsItem = res.resultInfo
        let str = `
        <div id="aaaa">
        <div class="main">
          <div class="left">
            <div class="showBox">
        `

        goodsItem.list.forEach((item, index) => {
          let img = `<img id="bigimg" src="${item}" alt="" ${index != 0 ? 'class="active"' : ''} ></img>`
          str += img
        })
        str += ` 
        <div class="show1 active" style="position: absolute;top: 0;left: 0;"}></div>
      </div>

      <ul id="list">`

        goodsItem.list.forEach((item, index) => {
          let img1 = `
        <li>
          <img src="${item}" id="${index + 1}" style="height:50px;width:50px" alt="">
        </li>
        `
          str += img1
        })

        str += ` </ul>
      </div>
  
      <div class="reight vis">`

        goodsItem.list.forEach((item, index) => {
          let img2 = ` 
        <img src="${item}"alt="" ${index == 0 ? 'style="position: relative;top: 0;left: 0;" name="a"' : 'class="active"'}>
        
        `
          str += img2
        })
        str += `

      </div>
        
      <div class="content">
        <h1>店家：${goodsItem.shop}</h1>

        <h2>${goodsItem.product}</h2>

        <h3>
          店家介绍：${goodsItem.detail}
        </h3>

        <button class="toshopping" data-index="${goodsItem.id}">加入购物车</button>

        <div>
          <span>
            <span>秒杀价:${goodsItem.price}</span> <span>原价:${goodsItem.oldprice}</span>
          </span>
          <span>海鲜</span>
        </div>
      </div>
    </div>
  </div>
      `



        // 改变当前位置
        document.querySelector('.goodsListHeader').innerHTML = `当前位置：详情/${res.resultInfo.product}`

        document.querySelector('.goodsList').innerHTML = str

        // 隐藏查看更多
        document.querySelector('.more>button').setAttribute('id', 'show')

        document.querySelector('#toStart>ul>li:nth-child(3)').setAttribute('class', ' ')

        //实例化放大镜类
        let show = new Showimg('.main')
        show.setImg()
        show.moveMouse()
        gocat(goodsItem)
      }).catch(err => {
        console.log(err);
      })
    }
    to()
  })
}


/* 
  加入购物
*/
function gocat(goods) { 


  let usregoods
  if(localStorage.getItem(getCookie('username'))){
    usregoods = JSON.parse(localStorage.getItem(getCookie('username')))
  }else{
    usregoods = []
  }
  document.querySelector('#aaaa .toshopping').onclick = function () {  
    if (userinfo()) {
      let item = {
        id:goods.id,
        name:goods.product,
        url:goods.picture,
        price:goods.price,
        num:0,
        singlePrice:0,
        state:false
      }
  
      let isHas = usregoods.some(items => {
        return items.id == item.id
      })
  
      if (!isHas) {
        usregoods.push(item)
        localStorage.setItem(getCookie('username'),JSON.stringify(usregoods))
        alert('已加入购物车')
      }else{
        alert('你已经添加购物车，请跳转购物车查看')
      }
    }else{
      alert('请登录')
    }
  }
}


/* 
  滚动到导航位置
*/
function to() {
  let t = setInterval(function () {
    if (document.documentElement.scrollTop < 580) {
      document.documentElement.scrollTop += 30
    } else {
      document.documentElement.scrollTop = 580
      clearInterval(t)
    }
  }, 8)
}


//放大镜类
class Showimg {
  constructor(id) {
    this.bigClass = document.querySelector(id) // 大盒子
    this.smalls = this.bigClass.querySelectorAll('li>img') //小图片
    this.shows = this.bigClass.querySelectorAll('.showBox>img') //中图片
    this.bigs = this.bigClass.querySelectorAll('.reight>img') //大图
    this.showbox = this.bigClass.querySelector('.showBox')
    this.show = this.bigClass.querySelector('.show1')
    this.reight = this.bigClass.querySelector('.reight')
  }

  // 切换图片
  setImg() {
    let _this = this
    this.bigClass.addEventListener('click', (e) => {
      e = e || window.event
      let target = e.target || e.srcElement
      // console.log(target.id);
      if (target.parentElement.parentElement.id == 'list') {
        for (let i = 0; i < this.shows.length; i++) {
          this.shows[i].classList.add('active')
          if (i == target.id - 1) {
            this.shows[i].classList.remove('active')
          }
        }
        for (let j = 0; j < this.bigs.length; j++) {
          this.bigs[j].classList.add('active')
          this.bigs[j].style.position = ''
          this.bigs[j].style.top = ''
          this.bigs[j].style.left = ''
          this.bigs[j].setAttribute('name', '')
          if (j == target.id - 1) {
            this.bigs[j].classList.remove('active')
            this.bigs[j].style.position = 'relative'
            this.bigs[j].style.top = 0
            this.bigs[j].style.left = 0
            this.bigs[j].setAttribute('name', 'a')
          }
        }

      }
    })
  }

  //放大镜效果
  moveMouse() {
    this.showbox.addEventListener('mousemove', (e) => {
      e = e || window.event
      let x = e.offsetX
      let y = e.offsetY
      let elex = getComputedStyle(this.show).top
      let eley = getComputedStyle(this.show).left


      let big = this.bigClass.querySelector('img[name="a"]')
      big.style.top = -y * 1.5 + 'px'
      big.style.left = -x * 1.5 + 'px'

      if (x <= 75) {
        x = 75
      }
      if (x >= 275) {
        x = 275
      }
      if (y <= 75) {
        y = 75
      }
      if (y >= 275) {
        y = 275
      }
      this.show.classList.remove('active')

      this.reight.classList.remove('vis')
      this.show.style.top = y - 75 + 'px'
      this.show.style.left = x - 75 + 'px'




    })
    this.showbox.addEventListener('mouseout', () => {
      this.show.classList.add('active')
      this.reight.classList.add('vis')
    })

  }

}



/* 
  进入购物车
*/

function goshopping() {  
  document.querySelector('.banner').addEventListener('click',function (e) {  
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.innerHTML == "购物车") {
      if (userinfo()) {
        location.href = './shopping.html'
      }else{
        alert('请登录')
      }
    }
  })
  document.querySelector('#toStart').addEventListener('click',function (e) {  
    e = e || window.event
    let target = e.target || e.srcElement
    if (target.innerHTML == "购物车") {
      if (userinfo()) {
        location.href = './shopping.html'
      }else{
        alert('请登录')
      }
    }
  })
  
}


userinfo()
goTop()
gohome()
banner()
getFenLei()
getbanner()
getGoods()
showMore()
showFenleiList()
keysearch()
search()
showweizhi()
login()
showinfo()
goshopping()
